#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
运行所有测试

这个文件会依次运行所有测试模块，提供完整的测试报告
"""

import sys
import os
from loguru import logger

# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 强制导入配置，确保镜像环境变量已设置
import questionretrieval.config

logger.info("🌐 使用 HuggingFace 国内镜像配置")
logger.info(f"📁 缓存目录: {questionretrieval.config.HF_HUB_CACHE}")
logger.info(f"🔗 镜像地址: {questionretrieval.config.HF_MIRROR_ENDPOINT}")

def run_all_tests():
    """
    运行所有测试
    """
    logger.info("\n" + "="*60)
    logger.info("Question Retrieval 系统完整测试")
    logger.info("="*60)
    
    # 导入测试模块
    try:
        from test_data_loading import test_data_loading, test_data_loading_with_custom_path
        from test_retriever_init import test_all_retrievers_init
        from test_question_loading import test_all_retrievers_load_questions
        from test_recommendation import test_all_retrievers_recommend
        from test_similarity_methods import test_all_similarity_methods
        from test_bert_similarity_features import test_all_bert_similarity_features
        from test_clustering_features import test_all_clustering_features
    except ImportError as e:
        logger.error(f"✗ 导入测试模块失败: {e}")
        logger.info("请确保在正确的目录下运行此脚本")
        return
    
    # 1. 数据加载测试
    logger.info("\n" + "="*50)
    logger.info("第一步: 数据加载测试")
    logger.info("="*50)
    
    data_results = {
        '默认数据加载': test_data_loading(),
        '自定义路径加载': test_data_loading_with_custom_path()
    }
    
    # 2. 检索器初始化测试
    logger.info("\n" + "="*50)
    logger.info("第二步: 检索器初始化测试")
    logger.info("="*50)
    
    init_results = test_all_retrievers_init()
    
    # 3. 问题加载测试
    logger.info("\n" + "="*50)
    logger.info("第三步: 问题加载测试")
    logger.info("="*50)
    
    loading_results = test_all_retrievers_load_questions()
    
    # 4. 推荐功能测试
    logger.info("\n" + "="*50)
    logger.info("第四步: 推荐功能测试")
    logger.info("="*50)
    
    recommend_results = test_all_retrievers_recommend()
    
    # 5. 相似度方法测试
    logger.info("\n" + "="*50)
    logger.info("第五步: 相似度方法测试")
    logger.info("="*50)
    
    similarity_results = test_all_similarity_methods()
    
    # 6. BERT相似度功能测试
    logger.info("\n" + "="*50)
    logger.info("第六步: BERT相似度功能测试")
    logger.info("="*50)
    
    bert_similarity_results = test_all_bert_similarity_features()
    
    # 7. 聚类功能测试
    logger.info("\n" + "="*50)
    logger.info("第七步: 聚类功能测试")
    logger.info("="*50)
    
    clustering_results = test_all_clustering_features()
    
    # 生成完整报告
    logger.info("\n" + "="*60)
    logger.info("完整测试报告")
    logger.info("="*60)
    
    logger.info("\n📊 数据加载测试:")
    for test_name, success in data_results.items():
        status = "✓ 通过" if success else "✗ 失败"
        logger.info(f"  {test_name:15} : {status}")
    
    logger.info("\n🔧 检索器初始化测试:")
    for retriever_name, success in init_results.items():
        status = "✓ 成功" if success else "✗ 失败"
        logger.info(f"  {retriever_name:20} : {status}")
    
    logger.info("\n📚 问题加载测试:")
    for retriever_name, success in loading_results.items():
        status = "✓ 成功" if success else "✗ 失败"
        logger.info(f"  {retriever_name:20} : {status}")
    
    logger.info("\n🎯 推荐功能测试:")
    for retriever_name, success in recommend_results.items():
        status = "✓ 成功" if success else "✗ 失败"
        logger.info(f"  {retriever_name:20} : {status}")
    
    logger.info("\n🔍 相似度方法测试:")
    for method_name, success in similarity_results.items():
        status = "✓ 成功" if success else "✗ 失败"
        logger.info(f"  {method_name:20} : {status}")
    
    logger.info("\n🤖 BERT相似度功能测试:")
    for feature_name, success in bert_similarity_results.items():
        status = "✓ 成功" if success else "✗ 失败"
        logger.info(f"  {feature_name:20} : {status}")
    
    logger.info("\n🔗 聚类功能测试:")
    for feature_name, success in clustering_results.items():
        status = "✓ 成功" if success else "✗ 失败"
        logger.info(f"  {feature_name:20} : {status}")
    
    # 统计可用的检索器
    available_retrievers = []
    for retriever_name in init_results.keys():
        if (init_results[retriever_name] and 
            loading_results[retriever_name] and 
            recommend_results[retriever_name]):
            available_retrievers.append(retriever_name)
    
    logger.info("\n" + "-"*60)
    logger.info("总结")
    logger.info("-"*60)
    
    data_success = sum(data_results.values())
    total_data_tests = len(data_results)
    similarity_success = sum(similarity_results.values())
    total_similarity_tests = len(similarity_results)
    bert_similarity_success = sum(bert_similarity_results.values())
    total_bert_similarity_tests = len(bert_similarity_results)
    clustering_success = sum(clustering_results.values())
    total_clustering_tests = len(clustering_results)
    
    logger.info(f"📊 数据加载: {data_success}/{total_data_tests} 个测试通过")
    logger.info(f"🔧 可用检索器: {len(available_retrievers)}/{len(init_results)} 个")
    logger.info(f"🔍 相似度方法: {similarity_success}/{total_similarity_tests} 个测试通过")
    logger.info(f"🤖 BERT相似度功能: {bert_similarity_success}/{total_bert_similarity_tests} 个测试通过")
    logger.info(f"🔗 聚类功能: {clustering_success}/{total_clustering_tests} 个测试通过")
    
    if available_retrievers:
        logger.info(f"\n🎉 恭喜! 以下检索器完全可用:")
        for retriever in available_retrievers:
            logger.info(f"  ✓ {retriever}")
        logger.info("\n💡 你可以在项目中使用这些检索器进行问答检索")
    else:
        logger.warning("\n⚠️  没有完全可用的检索器")
        logger.info("\n解决方案:")
        logger.info("1. 安装必要依赖:")
        logger.info("   pip install transformers sentence-transformers torch")
        logger.info("2. 确保网络连接正常 (首次使用需要下载模型)")
        logger.info("3. 检查Python版本兼容性")
    
    logger.info("\n" + "="*60)
    logger.info("测试完成")
    logger.info("="*60)

if __name__ == "__main__":
    run_all_tests()